package cn.shuangbofu.guice.test;

import com.google.common.collect.Maps;
import com.google.inject.Singleton;

import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created by shuangbofu on 2020-04-17 15:00
 */
@Singleton
public class EntityQueue {

    private PriorityBlockingQueue<Entity> queue = new PriorityBlockingQueue<>(100, Comparator.comparingInt(Entity::getPriority));
    private Map<Entity, Pair<Integer, Boolean>> ballPool;

    public EntityQueue() {
        ballPool = Maps.newConcurrentMap();
    }

    public void startRubBall() {
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                for (Entity entity : queue) {
                    int size = entity.rubBalls();
                    int newSize = ballPool.get(entity).getFirst() + size;
                    ballPool.put(entity, new Pair<>(newSize, true));
                }
                System.out.println("rubBall");
            }
        }).run();
    }

    public void put(Entity entity) {
        ballPool.put(entity, new Pair<>(0, true));
        queue.put(entity);
    }

    public Entity get() {
        Entity entity = null;
        try {
            entity = queue.take();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (entity != null) {
            Integer size = ballPool.get(entity).getFirst();
            ballPool.put(entity, new Pair<>(size, false));
            System.out.println(entity.getName() + "消失了");
        }
        return entity;
    }

    public Map<Entity, Pair<Integer, Boolean>> getTotal() {
        return ballPool;
    }
}
